﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using UDS.Components;
using UDS.Entity;

namespace UDS.SubModule.UnitiveDocument.DocumentFlowPages
{
    /// <summary>
    /// NewDocument 的摘要说明。
    /// </summary>
    public partial class NewDocumentPage : Page
    {
        private int _docId;
        private int _flowId;
        private string _userName;
        private DocumentInfo _currentDoc;
        private bool _isFlowByProject;

        protected FlowStyle CurrentFlowStyle
        {
            get;
            private set;
        }

        protected Flow CurrentFlow
        {
            get;
            private set;
        }

        protected override void OnInit(EventArgs e)
        {
            // Add event handlers to buttons
            cmdSave.Click += cmdSave_Click;
            cmdSend.Click += cmdSend_Click;
            cmdDelete.Click += cmdDelete_Click;

            _flowId = QSUtil.GetPositiveInt32("FlowID");
            _userName = SiteContext.Current.UserName;

            _docId = QSUtil.GetPositiveInt32("DocID");
            if (_docId > 0)
            {
                _currentDoc = DocumentInfo.GetDocumentInfo(_docId);
                if (_currentDoc != null)
                {
                    _flowId = _currentDoc.FlowID;
                }
            }

            CurrentFlow = Flow.GetFlow(_flowId);
            CurrentFlowStyle = FlowStyle.GetFlowStyle(CurrentFlow.StyleID);

            Bind();
            base.OnInit(e);
        }

        private void Bind()
        {
            #region buttons
            _isFlowByProject = false;
            if (_currentDoc != null)
            {
                //读取稿件内容
                cmdSend.Enabled = true;
                cmdDelete.Enabled = true;

                // Determines whether the flow rule of the document is by project?
                _isFlowByProject = DocumentInfo.IsFlowByProject(_userName, _docId);
                if (_isFlowByProject)
                {
                    var projects = Project.GetProjects(_userName);

                    ddlProject.Visible = true;
                    ddlProject.Items.Clear();
                    foreach (var p in projects)
                    {
                        ddlProject.Items.Add(new ListItem(p.Name, p.ID.ToString()));
                    }
                }
                else
                {
                    // Hide the project list
                    ddlProject.Visible = false;
                    ddlProject.EnableViewState = false;
                }
            }
            else
            {
                cmdSend.Enabled = false;
                cmdDelete.Enabled = false;
                ddlProject.EnableViewState = false;
                ddlProject.Visible = false;
            }
            #endregion

            // Fields to be filled
            fieldRepeater.ItemDataBound += delegate(object sender, RepeaterItemEventArgs e)
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    TextBox textBox = (TextBox)e.Item.FindControl("fieldValue");
                    textBox.Attributes["FieldName"] = ((FlowStyleDescription)e.Item.DataItem).Name;
                }
            };
            var list = FlowStyleDescription.GetStyleDescriptionByFlow(_flowId);
            fieldRepeater.DataSource = list;
            fieldRepeater.DataBind();

            if (_docId > 0)
            {
                // Attachments 
                attachmentRepeater.DataSource = DocumentFile.GetAttachments(_docId);
                attachmentRepeater.DataBind();
            }

            templateRow.Visible = (CurrentFlowStyle != null && !string.IsNullOrEmpty(CurrentFlowStyle.Template));
            projectRow.Visible = ddlProject.Visible;

            //=============================//
            //			添加批注
            //=============================//
            var postils = DocumentPostil.GetDocumentPostils(_docId);
            postilRepeater.Visible = (postils.Count > 0);       // Hidden the repeater if there are no postils.
            if (postilRepeater.Visible)
            {
                postilRepeater.DataSource = postils;
                postilRepeater.DataBind();
            }
        }

        protected string GetHeadline()
        {
            return Flow.GetFlowHeadline(_flowId);
        }

        protected string GetFieldValue(FlowStyleDescription field)
        {
            if (_docId > 0)
            {
                return (_currentDoc != null && _currentDoc.Data != null) ? _currentDoc.Data[field.Name] : "不存在";
            }
            return string.Empty;
        }

        protected string FormatPostilAttachmentLink(DocumentPostil p)
        {
            if (p != null && p.File != null)
            {
                string path = p.File.FullVirtualPath;
                if (!string.IsNullOrEmpty(path))
                {
                    return "<a href='" + HttpUtility.HtmlAttributeEncode(ResolveUrl(path)) + "' target='_blank'>" + HttpUtility.HtmlEncode(p.File.FileName) + "</a>";
                }
            }
            return "&nbsp;";
        }

#if false
        private void UploadFile(int docId, Database db)
        {
            string FileName;

            //生成附件目录
            if (fileUpload != null && fileUpload.PostedFile != null)
            {
                if (fileUpload.PostedFile.FileName.Trim() != "")
                {
                    FileName = Path.GetFileName(fileUpload.PostedFile.FileName);

                    //生成用户目录
                    var userDirVPath = Utility.CombineVirtualDirs(DocAttachFile.AttachVDir, _userName);
                    var userDir = new DirectoryInfo(MapPath(userDirVPath));
                    if (!userDir.Exists)
                    {
                        userDir.Create();
                    }

                    string NewDocDirName = string.Format("{0:yyyyMMdd_HHmmss}_{1:0000}", DateTime.Now, Utility.GetRandomNumber(10000));

                    //生成随机目录
                    var tmpDirVPath = Utility.CombineVirtualDirs(userDirVPath, NewDocDirName);
                    var tmpDir = new DirectoryInfo(MapPath(tmpDirVPath));
                    if (!tmpDir.Exists)
                    {
                        tmpDir.Create();
                    }

                    //保存文件
                    fileUpload.PostedFile.SaveAs(Path.Combine(tmpDir.FullName, FileName));

                    var att = new DocumentFile();
                    var df = new DocumentFlow();

                    // 初始化
                    att.FileAttribute = 0;
                    att.FileSize = fileUpload.PostedFile.ContentLength;
                    att.FileName = FileName;
                    att.Author = _userName;
                    att.Catalog = "公文";
                    att.FileVisualPath = tmpDirVPath;
                    att.TimeCreated = DateTime.Now;

                    DocumentFlow.AddAttach(db, att, docId);
                }
            }
        }
#endif

        private void GetStyleData(out string[] styleDataNames, out string[] styleDataValues)
        {
            var names = new List<string>();
            var values = new List<string>();
            foreach (RepeaterItem item in fieldRepeater.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    TextBox textBox = (TextBox)item.FindControl("fieldValue");
                    names.Add(textBox.Attributes["FieldName"]);
                    values.Add(textBox.Text);
                }
            }

            styleDataNames = names.ToArray();
            styleDataValues = values.ToArray();
        }

        #region event handlers
        private void cmdSend_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                //发送到下一环节，使程序处于运行中
                int projectId = 0;
                if (_isFlowByProject)
                {
                    if (ddlProject.Items.Count == 0)
                    {
                        SiteContext.Current.Alert("用户没有一个项目，不能按项目发送！");
                        return;
                    }

                    projectId = int.Parse(ddlProject.SelectedValue);
                }

                int iResult = DocumentInfo.PostDocument(_userName, _docId, projectId);

                if (iResult == 0)
                {
                    Response.Redirect("DisplayDocument.aspx?DocID=" + _docId);
                }
                else
                {
                    SiteContext.Current.Alert(DocumentInfo.GetErrorMessage(iResult, _docId, false));
                }
            }
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            DocumentFlow.DeleteDocument(_docId);
            Response.Redirect("FlowTemplate.aspx");
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                string[] names;
                string[] values;
                string redirectUrl = null;

                GetStyleData(out names, out values);
                if (_currentDoc == null)
                {
                    try
                    {
                        _docId = DocumentInfo.AddDocument(_userName, _flowId, names, values, fileUpload.PostedFile);

                        //转到查看稿件
                        redirectUrl = string.Format("NewDocument.aspx?FlowID={0}&DocID={1}", _flowId, _docId);
                    }
                    catch (Exception ex)
                    {
                        SiteContext.Current.AlertException("创建稿件失败", ex);
                    }
                }
                else
                {
                    try
                    {
                        DocumentInfo.UpdateDocument(_docId, _userName, names, values, fileUpload.PostedFile);
                    }
                    catch (Exception ex)
                    {
                        SiteContext.Current.AlertException("更新稿件失败。", ex);
                    }
                }

                if (redirectUrl != null)
                {
                    Response.Redirect(redirectUrl);
                }
            }
        }
        #endregion event handlers
    }
}